/**
 * 删除文件
 */

import React from 'react';
import { Dialog, Field, Message, Balloon } from '@teamix/ui';
import { ButtonIcon } from '@alife/devops-ui';
import { navigate } from 'utils/router';
import FileBasicForm from 'components/fileBasicForm';
import utils from 'utils';
import UILessAssociateTask from 'components/UILessAssociateTask';
import NotBranchDisabledButton from '../components/notBranchDisabledButton';
import intl from '../../../../../../../../../locale';

const { pathResource, resourceSubject } = window.FORCE;
const { Tooltip } = Balloon;

export default class DeleteFile extends React.Component {
  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      isDialogVisible: false,
      submitting: false,
      task_ids: '',
    };
  }

  onDialogOpen = () => {
    this.setState({ isDialogVisible: true });
  };

  onDialogOk = () => {
    if (this.state.submitting) return;
    this.setState({ submitting: true });
    this.field.validate((errors) => {
      if (!errors) {
        const formData = this.field.getValues();
        if (this.state.task_ids) {
          formData.task_ids = this.state.task_ids;
        }
        const commit_message = formData.commit_message_content
          ? `${formData.commit_message_title}\n${formData.commit_message_content}`
          : formData.commit_message_title;
        this.props.deleteFile(formData, commit_message, (succ) => {
          if (succ) {
            Message.success({
              title: intl.get({
                id: 'code-assets.content.dialog.deleteFile.FileWasDeleted',
                defaultMessage: '文件已删除',
              }),
            });

            this.props.updateData({
              hasPush: true,
            });

            navigate(
              `/${pathResource.fullPath}/tree/${utils.revisionEncodeURI(
                resourceSubject.revision,
              )}/`,
              { state: { forceUpdate: true } },
            );
          } else {
            this.setState({ submitting: false });
          }
        });
      } else {
        this.setState({ submitting: false });
      }
    });
  };

  onDialogCancel = () => {
    this.setState({
      isDialogVisible: false,
    });
  };

  render() {
    const { resourcePath } = this.props;
    const { revisionType } = resourceSubject;
    const resourcePathArr = resourcePath.split('/');
    const fileName = resourcePathArr[resourcePathArr.length - 1];

    const deleteText = `${intl.get({
      id: 'code-assets.src.utils.locale.Delete',
      defaultMessage: '删除',
    })} ${fileName}`;
    return (
      <React.Fragment>
        {revisionType !== 'branch' ? (
          <NotBranchDisabledButton
            tooltipText={intl.get({
              id: 'code-assets.content.dialog.deleteFile.OnlyFilesUnderBranchesCan',
              defaultMessage: '只有分支下的文件可以被删除',
            })}
            isIcon
            name="delete-line"
            className="file-icon-margin-left"
          />
        ) : (
          <Tooltip
            trigger={
              <ButtonIcon
                name="delete-line"
                className="file-icon-margin-left"
                onClick={this.onDialogOpen}
              />
            }
            text={intl.get({
              id: 'code-assets.content.dialog.deleteFile.Delete',
              defaultMessage: '删除',
            })}
            align="t"
          />
        )}

        <Dialog
          visible={this.state.isDialogVisible}
          onOk={this.onDialogOk}
          onCancel={this.onDialogCancel}
          onClose={this.onDialogCancel}
          title={
            <Tooltip
              trigger={
                <div className="file-form-title">
                  {intl.get({
                    id: 'code-assets.content.dialog.deleteFile.Submit',
                    defaultMessage: '提交到',
                  })}
                  {resourceSubject.revision}
                </div>
              }
              align="t"
            >
              <span style={{ wordBreak: 'break-all' }}>
                {intl.get({
                  id: 'code-assets.content.dialog.deleteFile.Submit',
                  defaultMessage: '提交到',
                })}
                {resourceSubject.revision}
              </span>
            </Tooltip>
          }
          style={{
            width: '600px',
          }}
          okProps={{
            children: intl.get({
              id: 'code-assets.content.dialog.deleteFile.Submitted',
              defaultMessage: '提交',
            }),
            loading: this.state.submitting,
          }}
          cancelProps={{
            children: intl.get({
              id: 'code-assets.content.dialog.deleteFile.Cancel',
              defaultMessage: '取消',
            }),
          }}
        >
          <Message
            type="warning"
            style={{ marginBottom: '12px' }}
            title={intl.get(
              {
                id: 'code-assets.content.dialog.deleteFile.AfterTheInformationIsSubmitted',
                defaultMessage: '提交完信息将从库内删除文件 {fileName}',
              },
              { fileName },
            )}
          />
          <FileBasicForm field={this.field} defaultCommitMsg={deleteText} />

          <UILessAssociateTask
            useBy="submit"
            onChange={(items) => {
              if (!items.map) {
                return;
              }
              const task_ids = items.map((item) => {
                return item._id;
              });
              this.setState({
                task_ids: task_ids.join(','),
              });
            }}
          />
        </Dialog>
      </React.Fragment>
    );
  }
}
